package judesart.app.authentication;

import javax.inject.Inject;

import judesart.app.domain.User;
import judesart.app.repository.UserDAO;
import judesart.app.service.UserService;
import judesart.app.shared.ValidationException;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("AuthenticationService")
public class AuthenticationService implements UserDetailsService
{
    @Inject
    private UserDAO userDAO;

    @Inject
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException
    {
        if (userDAO.findUserByUsername("admin") == null)
        {
            try
            {
                userService.createAdminUser();
            } catch (ValidationException ex)
            {
                ex.printStackTrace();
            }
        }
        User user = userDAO.findUserByUsername(username);
        if (user == null)
        {
            throw new UsernameNotFoundException("Username [" + username
                    + "] not found.");
        }
        return new AuthUserDetails(user);
    }

}
